package org.lhh.server.core.repository;

import org.lhh.server.config.web.exception.EtlException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class EtlServiceProxy implements InvocationHandler {

    private EtlService service;

    EtlServiceProxy(EtlService service) {
        this.service = service;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        Object invoke;
        try {
            invoke = method.invoke(service, args);
        } catch (IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof EtlException)
                throw new EtlException(cause.getMessage());
            else
                throw e;
        } finally {
            EtlRepository.closeRepository((EtlKettleDatabaseRepository) args[args.length - 1]);
        }
        return invoke;
    }

}
